package com.company;

import java.io.*;

public class MyClassLoader extends ClassLoader {

    private File classPathFile;

    public MyClassLoader() {
        // 绝对路径
        String path = MyClassLoader.class.getResource("").getPath();
        this.classPathFile = new File(path);
    }


    protected Class<?> findClass(String name) {
        // 获取class 的Name 包名+Java类名
        String className = MyClassLoader.class.getPackage().getName() + "." + name;

        if (this.classPathFile != null) {
            // 读取class文件
            File file = new File(this.classPathFile, name.replaceAll("\\.", "/") + ".class");

            if (file.exists()) {
                FileInputStream in = null;
                ByteArrayOutputStream out = null;

                try {
                    in = new FileInputStream(file);
                    out = new ByteArrayOutputStream();

                    byte[] buff = new byte[1024];
                    int len;

                    while ((len = in.read(buff)) != -1) {
                        out.write(buff, 0, len);
                    }
                    // 调用父类方法 生成class对象
                    return defineClass(className, out.toByteArray(), 0, out.size());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

}
